package com.wnxy.admin.controller;

import cn.hutool.core.lang.UUID;
import com.wnxy.admin.common.ResponseResult;
import com.wnxy.admin.common.handler.Asserts;
import com.wnxy.admin.common.handler.BusinessEnum;
import com.wnxy.admin.common.util.AliOssUtil;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.IOUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/common")
@RequiredArgsConstructor
public class CommonController {
    // 自动装配阿里云oss工具类
    private final AliOssUtil aliOssUtil;
    private final RedisTemplate<String, String> redisTemplate;


    @PostMapping("/upload")
    @ApiOperation("图片上传")
    public ResponseResult upload(@RequestParam("file") MultipartFile[] files) {
        List<String> filePaths = new ArrayList<>();
        try {
            for (MultipartFile file : files) {
                // 检查文件大小
                Asserts.fail(file.getSize() > 1 * 1024 * 1024, BusinessEnum.FILE_SIZE_EXCEEDED_LIMIT);
                // 检查文件是否为图片（JPEG 或 PNG）
                Asserts.fail(!isImageFile(file), BusinessEnum.ONLY_JPG_OR_PNG_CAN_BE_UPLOADED);

                // 原始文件名
                String originalFilename = file.getOriginalFilename();
                // 构造新文件名称
                String objectName = UUID.randomUUID().toString().replace("-", "") + "_" + originalFilename;
                // 返回文件请求路径
                String filePath = aliOssUtil.upload(file.getBytes(), objectName);
                // 存储在 Redis 中
                redisTemplate.opsForSet().add("upload-file-all", filePath);

                filePaths.add(filePath);
            }
            return ResponseResult.ok(filePaths);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseResult.fail(BusinessEnum.FILE_UPLOAD_FAILED);
    }

    private boolean isImageFile(MultipartFile file) throws IOException {
        // 通过读取文件头检查文件类型
        byte[] header = new byte[8];
        IOUtils.read(file.getInputStream(), header);
        // 检查文件是否以 JPEG 或 PNG 文件签名开头
        return isJpeg(header) || isPng(header);
    }

    private boolean isJpeg(byte[] header) {
        return header[0] == (byte) 0xFF && header[1] == (byte) 0xD8;
    }

    private boolean isPng(byte[] header) {
        return header[0] == (byte) 0x89 && header[1] == (byte) 0x50 && header[2] == (byte) 0x4E &&
                header[3] == (byte) 0x47 && header[4] == (byte) 0x0D && header[5] == (byte) 0x0A &&
                header[6] == (byte) 0x1A && header[7] == (byte) 0x0A;
    }
}
